package com.xge.business.utils

import java.text.SimpleDateFormat
import java.util.*

object ConstellationUtils {

    private val dateFullFormat = SimpleDateFormat("yyyy-MM-dd", Locale.CHINA)
    private val dateShortFormat = SimpleDateFormat("MM-dd", Locale.CHINA)

    private val constellations = arrayOf(
        "摩羯座", "水瓶座", "双鱼座", "白羊座", "金牛座", "双子座",
        "巨蟹座", "狮子座", "处女座", "天秤座", "天蝎座", "射手座", "摩羯座"
    )

    private val constellationEdgeDays = intArrayOf(
        20, 19, 21, 20, 21, 22,
        23, 23, 23, 24, 23, 22
    )

    /**
     * 传入格式 yyyy-MM-dd 或 MM-dd，返回星座名称
     */
    fun getConstellation(dateStr: String): String {
        val (month, day) = parseMonthDay(dateStr) ?: return "000" //日期格式错误
        if (!isValidDate(month, day)) return "111" //日期不合法
        return getConstellationByMonthDay(month, day)
    }

    private fun parseMonthDay(input: String): Pair<Int, Int>? {
        return try {
            when {
                input.matches(Regex("\\d{4}-\\d{1,2}-\\d{1,2}")) -> {
                    val date = dateFullFormat.parse(input)
                    val calendar = Calendar.getInstance().apply { time = date!! }
                    Pair(calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH))
                }

                input.matches(Regex("\\d{1,2}-\\d{1,2}")) -> {
                    val date = dateShortFormat.parse(input)
                    val calendar = Calendar.getInstance().apply { time = date!! }
                    Pair(calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH))
                }

                else -> null
            }
        } catch (e: Exception) {
            null
        }
    }

    private fun isValidDate(month: Int, day: Int): Boolean {
        return try {
            val dateStr = String.format("%02d-%02d", month, day)
            dateShortFormat.isLenient = false
            dateShortFormat.parse(dateStr)
            true
        } catch (e: Exception) {
            false
        }
    }

    private fun getConstellationByMonthDay(month: Int, day: Int): String {
        val index = if (day < constellationEdgeDays[month - 1]) month - 1 else month
        return constellations[index]
    }
}
